import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:t_upgrade_plugin/bloc/app_version_bloc.dart';
import 'package:common/global/app_flavor.dart';
import 'package:common/global/global_blocs.dart';
import 'package:common/global/style.dart';

class UpgradeDialog extends StatefulWidget {
  @override
  _UpgradeDialogState createState() => _UpgradeDialogState();

  static show(BuildContext context) {
    showDialog(
        barrierDismissible: false,
        context: context,
        child: Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            child: UpgradeDialog()));
  }
}

class _UpgradeDialogState extends State<UpgradeDialog> {
  final _bloc = GlobalBlocs.get(AppVersionBloc.blocName);
  TextStyle contentTextStyle = TextStyle(color: Color(0xFF6F7275), fontSize: 14);
  TextStyle buttonStyle = TextStyle(fontSize: 14, color: TColor.primeColor);
  double bottomHeight = 45;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AppVersionBloc, AppVersionState>(
      cubit: _bloc,
      builder: (context, state) {
        return WillPopScope(
          // ignore: missing_return
          onWillPop: () async {
            if (state.updateType != UpdateType.FORCE) {
              Navigator.of(context).pop();
            }
          },
          child: Container(
            height: 180,
            width: (AppFlavor.flavor == Flavor.Machine||AppFlavor.flavor == Flavor.Maker) ? 200 : null,
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.only(top: 15),
                  child: Text(
                    '发现新版本',
                    style: TextStyle(color: TColor.textBlack, fontSize: 15, fontWeight: FontWeight.w500),
                  ),
                ),
                Expanded(
                  child: Center(child: Padding(padding: EdgeInsets.only(top: 5, bottom: 5), child: _buildContent(state))),
                ),
                Divider(height: 0.5, color: TColor.dividerGray),
                Visibility(
                    visible: state.downLoadType != DownLoadType.DOWNLOAD,
                    child: Container(height: bottomHeight, child: _bottomWidget(state)))
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildContent(AppVersionState state) {
    if (state.isManualCheck && state.downLoadType == DownLoadType.NON) {
      return Center(child: Text('当前版本为:${state.appVersion},最新版本为:${state.upgradeData.version}', style: contentTextStyle));
    }
    if (state.downLoadType == DownLoadType.NON) {
      return SingleChildScrollView(
          padding: EdgeInsets.only(left: 18, right: 18),
          child: Center(child: Text("${state.upgradeData.description ?? ''}", style: contentTextStyle)));
    } else if (state.downLoadType == DownLoadType.DOWNLOAD) {
      return _buildProgress(state);
    } else if (state.downLoadType == DownLoadType.DOWNLOAD_SUCCESS) {
      return Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.check_circle_outline, color: TColor.primeColor, size: 20),
            SizedBox(width: 3),
            Text('下载成功', style: contentTextStyle),
          ],
        ),
      );
    } else if (state.downLoadType == DownLoadType.ERROR) {
      return Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.highlight_off, color: Colors.red, size: 20),
            SizedBox(width: 3),
            Text('下载失败，请重试', style: contentTextStyle),
          ],
        ),
      );
    }
    return Container();
  }

  Widget _buildProgress(AppVersionState state) {
    return Padding(
      padding: EdgeInsets.only(left: 10, right: 10),
      child: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [
        Container(height: 20, child: Text("${(state.progress * 100).toStringAsFixed(0)}%", style: contentTextStyle)),
        LinearProgressIndicator(
          valueColor: AlwaysStoppedAnimation(TColor.primeColor),
          backgroundColor: TColor.backgroundColor,
          value: state.progress,
        ),
        SizedBox(height: 20),
      ]),
    );
  }

  Widget _bottomWidget(AppVersionState state) {
    if (state.downLoadType == DownLoadType.NON) {
      return _nonWidget(state);
    } else if (state.downLoadType == DownLoadType.DOWNLOAD) {
      return Container();
    } else if (state.downLoadType == DownLoadType.DOWNLOAD_SUCCESS) {
      return Center(
        child: FlatButton(
          onPressed: () => _bloc.add(InstallApkEvent()),
          child: Container(
            alignment: Alignment.center,
            height: bottomHeight,
            child: Text('立即安装', style: buttonStyle),
          ),
        ),
      );
    } else if (state.downLoadType == DownLoadType.ERROR) {
      return Center(
        child: FlatButton(
          onPressed: () => _bloc.add(NowUpdateEvent()),
          child: Container(
            alignment: Alignment.center,
            height: bottomHeight,
            child: Text('重试', style: buttonStyle),
          ),
        ),
      );
    }
    return Container();
  }

  Widget _nonWidget(AppVersionState state) {
    if (state.updateType == UpdateType.FORCE) {
      return Center(
        child: FlatButton(
          onPressed: () => _bloc.add(NowUpdateEvent()),
          child: Container(
            alignment: Alignment.center,
            height: bottomHeight,
            child: Text('更新', style: buttonStyle),
          ),
        ),
      );
    } else if (state.updateType == UpdateType.SIMPLE) {
      return Row(
        children: [
          Expanded(
            child: FlatButton(
                onPressed: () => Navigator.of(context).maybePop(),
                child: Center(child: Text(state.isManualCheck ? '取消' : '下次再说', style: buttonStyle))),
          ),
          VerticalDivider(width: 2, color: TColor.dividerGray),
          Expanded(
            child: FlatButton(
                onPressed: () => _bloc.add(NowUpdateEvent()), child: Center(child: Text('立即更新', style: buttonStyle))),
          )
        ],
      );
    } else if (state.updateType == UpdateType.IGNORE) {
      return Row(
        children: [
          Expanded(
            child: FlatButton(
                onPressed: () {
                  _bloc.add(IgnoreThisVersion());
                  Navigator.of(context).maybePop();
                },
                child: Center(child: Text(state.isManualCheck ? '取消' : '跳过该版本', style: buttonStyle))),
          ),
          VerticalDivider(width: 2, color: TColor.dividerGray),
          Expanded(
            child: FlatButton(
                onPressed: () => _bloc.add(NowUpdateEvent()), child: Center(child: Text('立即更新', style: buttonStyle))),
          )
        ],
      );
    }
    return Container();
  }

  @override
  void dispose() {
    super.dispose();
  }
}
